//
//  BCDebugTextEditPage.m
//  Pods
//
//  Created by Ye Qing on 16/11/5.
//
//

#import "BCDebugTextEditPage.h"
#import <BCFoundation/BCFoundationUtils.h>

#pragma mark > Configurable

typedef NS_ENUM(NSInteger, BCEditMode) {
    BCEditModeView,
    BCEditModeSearching,
    BCEditModeEditing,
};

typedef NS_ENUM(NSInteger, BCActionSheetType) {
    BCActionSheetTypeActions = 100,
    BCActionSheetTypeSimpleMatchActions,
    BCActionSheetTypeLetterCaseActions,
    BCActionSheetTypeSearchOrderActions,
};

typedef NS_ENUM(NSInteger, BCLetterCaseItemAction) {
    BCLetterCaseItemActionCaseInSensitive = 1,
    BCLetterCaseItemActionCaseSensitive,
};

typedef NS_ENUM(NSInteger, BCSimpleMatchItemAction) {
    BCSimpleMatchItemActionContaining = 1,
    BCSimpleMatchItemActionStartWith,
    BCSimpleMatchItemActionEndWith,
    BCSimpleMatchItemActionMatching,
};

typedef NS_ENUM(NSUInteger, BCSearchOrderAction) {
    BCSearchOrderActionFrontToEnd = 1,
    BCSearchOrderActionEndToFront,
    BCSearchOrderActionLoop,
};


//MARK: - BCDebugTextEditPage

@interface BCDebugTextEditPage () <UIActionSheetDelegate, UISearchBarDelegate>

@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) NSMutableAttributedString *attrTextM;
@property (nonatomic, strong) NSError *errorOfReadingFile;

@property (nonatomic, strong) NSMutableDictionary *searchInventoryM;
@property (nonatomic, assign) NSInteger searchKeyCurrentIndex;

@property (nonatomic, assign) NSRange currentHighlightRange;

@property (nonatomic, strong) UIColor *colorForAll;
@property (nonatomic, strong) UIColor *colorForCurrent;

@property (nonatomic, assign) BOOL statusBarHidden;
@property (nonatomic, assign) BCEditMode currentMode;
@property (nonatomic, assign) BCEditMode toMode;

@end

@implementation BCDebugTextEditPage

- (instancetype)initWithFilePath:(NSString *)filePath {
    self = [super init];
    if (self) {
        _filePath = filePath;
        _searchInventoryM = [NSMutableDictionary dictionary];
        _currentHighlightRange = NSMakeRange(0, 0);
        
        _colorForAll = [UIColor colorWithRed:0xFE / 255.0f green:0xD1 / 255.0f blue:0x52 / 255.0f alpha:1];
        _colorForCurrent = [UIColor colorWithRed:0xFF / 255.0f green:0x7A / 255.0f blue:0x38 / 255.0f alpha:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
    [self loadFile];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.errorOfReadingFile) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        NSError *error = self.errorOfReadingFile;
        NSLog(@"Error: %@", error);
        NSString *title = [NSString stringWithFormat:@"不能读取文件%@", [self.filePath lastPathComponent]];
        NSString *msg = [NSString stringWithFormat:@"code: %ld, %@", (long)error.code, error.localizedDescription];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
#pragma clang diagnostic pop
    } else {
        //延迟3s跳转到最底部
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.textView scrollRangeToVisible:NSMakeRange(self.textView.text.length-60, 50)];
//            if (self.textView.contentSize.height>self.textView.frame.size.height) {
//                [self.textView scrollRectToVisible:CGRectMake(0, self.textView.contentSize.height-self.textView.frame.size.height, self.textView.contentSize.width, self.textView.frame.size.height) animated:YES];
//            }
        });
    }
}


- (BOOL)prefersStatusBarHidden {
    // If self.statusBarHidden is TRUE, return YES. If FALSE, return NO.
    return (self.statusBarHidden) ? YES : NO;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

#pragma mark - Getters

- (UITextView *)textView {
    if (!_textView) {
        CGSize screenSize = [[UIScreen mainScreen] bounds].size;
        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height - kBCNAVBAR_HEIGHT)];
        textView.autocorrectionType = UITextAutocorrectionTypeNo;
        textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
        textView.editable = NO;
        textView.contentInset = UIEdgeInsetsMake(10, 5, 10, 5);
        _textView = textView;
    }
    
    return _textView;
}


#pragma mark

- (void)setup {
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingHead;
    
    NSDictionary *attrs = @{
                            NSFontAttributeName: [UIFont boldSystemFontOfSize:15.0f],
                            NSForegroundColorAttributeName: [UIColor darkTextColor],
                            //                            NSParagraphStyleAttributeName: paragraphStyle
                            };
    
    self.title = [self.filePath lastPathComponent];
    self.navigationController.navigationBar.titleTextAttributes = attrs;
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.textView];
}


- (void)loadFile {
    NSError *error = nil;
    NSString *text = [self readFileAtPath:self.filePath error:&error];
    if (!error) {
        self.attrTextM = [[NSMutableAttributedString alloc] initWithString:text];
        self.textView.attributedText = [self.attrTextM copy];
        self.textView.contentOffset = CGPointZero;
    }
    else {
        self.navigationItem.rightBarButtonItem = nil;
    }
    self.errorOfReadingFile = error;
}

- (NSString *)readFileAtPath:(NSString *)filePath error:(NSError **)error {
    NSString *fileName = [filePath lastPathComponent];
    NSString *fileExt = [[fileName pathExtension] lowercaseString];
    
    NSString *content;
    NSError *errorL;
    
    if ([fileExt isEqualToString:@"plist"]) {
        
        NSPropertyListFormat format = 0;
        NSData *data = [NSData dataWithContentsOfFile:filePath options:kNilOptions error:&errorL];
        if (data) {
            @try {
                id objectM = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:&format error:&errorL];
                content = [NSString stringWithFormat:@"%@", objectM];
            }
            @catch (NSException *exception) {
                NSLog(@"exception: %@", exception);
                NSString *reason = exception.reason ? exception.reason : @"文件读取异常";
                errorL = [NSError errorWithDomain:NSStringFromClass([self class]) code:-1 userInfo:@{ NSLocalizedDescriptionKey: reason }];
            }
        }
    }
    else {
        NSStringEncoding encoding = 0;
        // Treat as simple text file
        content = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&errorL];
    }
    
    *error = errorL;
    
    return content;
}

- (void)highlightAllWithFirstRange:(NSRange)firstRange searchKey:(NSString *)searchKey {
    
    NSArray *ranges = self.searchInventoryM[searchKey];
    
    if (ranges.count) {
        NSMutableAttributedString *attrString = [self.attrTextM mutableCopy];
        
        for (NSUInteger i = 0; i < ranges.count; i++) {
            NSRange range = [ranges[i] rangeValue];
            
            if (range.location == firstRange.location && range.length == firstRange.length) {
                // highlight first range
                if (firstRange.location != NSNotFound && firstRange.length == searchKey.length) {
                    self.currentHighlightRange = firstRange;
                    
                    [attrString setAttributes:@{ NSBackgroundColorAttributeName: self.colorForCurrent } range:firstRange];
                }
            }
            else {
                // highlight other ranges
                if (range.location != NSNotFound && range.length == searchKey.length) {
                    [attrString setAttributes:@{ NSBackgroundColorAttributeName: self.colorForAll } range:range];
                }
            }
        }
        
        self.textView.attributedText = attrString;
    }
}


- (void)setNavBackSwipeEnabled:(BOOL)enabled {
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = enabled;
    }
}


@end
